package eu.gline.km.clients;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import eu.gline.km.Core;
import eu.gline.km.actors.KeyboardActor;
import eu.gline.km.actors.MouseActor;

public class KmClient {
	
	private String hashName;
	private String hostname;
	private int port;
	private String password;
	
	private Core core;
	private Socket socket;
	private DataInputStream dis;
	private DataOutputStream dos;
	private KeyboardActor ka;
	private MouseActor ma;
	
	public KmClient(Core core, String hashName) {
		this.core = core;
	}

	public void createClient(String hostname, int port, String password) {
		this.hostname = hostname;
		this.port = port;
		this.password = password;
		try {
			closeConnection();
			socket = new Socket(hostname, port);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
	
	public DataInputStream getDis() {
		if (dis==null)
			try {
				dis = new DataInputStream(socket.getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		return dis;
	}
	
	public DataOutputStream getDos() {
		if (dos==null)
			try {
				dos = new DataOutputStream(socket.getOutputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
		return dos;
	}
	
	public boolean isConnected() {
		return (socket!=null) ? socket.isConnected() : false;
	}
	
	public void removeClient() {
		closeConnection();
		core.removeClient(hashName);
	}
	
	private void closeConnection() {
		dis=null;
		dos=null;
		if (socket != null && socket.isConnected())
			try {
				socket.close();
				socket = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	
	public void reconnect() {
		if (hostname!= null && port!=0) createClient(hostname, port, password);
	}
	
	public KeyboardActor getKeyboard() {
		if (ka==null) ka = new KeyboardActor(this);
		return ka;
	}
	
	public MouseActor getMouse() {
		if (ma==null) ma = new MouseActor(this);
		return ma;
	}
	
}
